package com.heima.wemedia.job;

import com.heima.common.constants.ScheduleConstants;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.schedule.feign.TaskFeign;
import com.heima.utils.common.JsonUtils;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 定时发布自媒体文章
 */
@Component
@Slf4j
public class WmNewsTaskJob{
    @Autowired
    private TaskFeign taskFeign;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 每秒检查Redis是否有发布的文章
     */
    @Scheduled(fixedRate = 1000)
    public void pollWmNewsTask(){
        //查询需要定时发布的文章任务
        List<Task> taskList = taskFeign.pollTask(ScheduleConstants.TASK_TOPIC_NEWS_PUBLISH);

        if(CollectionUtils.isNotEmpty(taskList)){
            for(Task task:taskList){
                String parameters = task.getParameters();
                WmNews wmNews = JsonUtils.toBean(parameters,WmNews.class);
                //根据id查询文章
                wmNews = wmNewsMapper.selectById(wmNews.getId());
                //发布文章
                wmNewsAutoScanService.publishApArticle(wmNews);
                log.info("定时文章已经成功发布 {}",task.getTaskId());
            }
        }
    }
}
